<template>
  <a-layout class="layout">
    <a-layout-header style="background-color: #139bd5;"></a-layout-header>
    <a-layout-content style="padding: 0 50px; width: 100%; height: 98%">
      <a-button
        type="link"
        style="background-color: #38b5e3; margin: 20px; color: #ffffff"
        @click="showAddModal"
      >
        添加学院
      </a-button>
      <div>
        <!-- 添加学院的模态框，运用基本模态框形式 -->
        <a-modal v-model:open="addModalVisible" title="新增院系专业" @ok="handleAddOk" ok-text="确定"
        cancel-text="取消">
          <a-form
            :model="addFormState"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            ref="addFormRef"
          >
            <a-form-item
              label="院系名称"
              name="name"
              :rules="[{ required: true, message: '请输入院系名称!' }]"
            >
              <a-input v-model:value="addFormState.name" />
            </a-form-item>
          </a-form>
        </a-modal>
      </div>
      <!-- 批量删除气泡框 -->
      <div style="margin-bottom: 16px">
        <a-popconfirm
          title="确定删除选中的所有项吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleBatchDelete"
        >
          <a-button type="link" :disabled="!hasSelected" :loading="state.batchDeleting" style="background-color: #edeceb; margin: 20px; color: #888">
           批量删除
          </a-button>
        </a-popconfirm>
      </div>
      <a-input-search
        placeholder="请输入院系名称"
        enter-button
        style="width: 200px; float: right; margin: 20px"
      ></a-input-search>
      <!-- 表格 -->
      <a-table :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :columns="columns" :data-source="formattedData" :pagination="false"> 
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a style="color: #139bd5;" @click="showEditModal(record)">编辑</a>
            <!-- 编辑模态框 -->
      <a-modal v-model:open="editModalOpen" title="编辑院系专业" @ok="handleEditOk" ok-text="确定"
      cancel-text="取消">
        <a-form
          :model="editFormState"
          name="editForm"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          ref="editFormRef"
        >
          <a-form-item
            label="院系名称"
            name="name"
            :rules="[{ required: true, message: '请输入院系名称!' }]"
          >
            <a-input v-model:value="editFormState.name" />
          </a-form-item>
        </a-form>
      </a-modal>
            <a-divider type="vertical" style="height: 20px; background-color: #ddd" />
            <!-- 操作里的删除及气泡框 -->
            <a-popconfirm title="确定删除吗？" ok-text="确定" cancel-text="取消" @confirm="() => handleDelete(record.id)">
              <a style="color: red">删除</a>
            </a-popconfirm>
            <a-divider type="vertical" style="height: 20px; background-color: #ddd" />
            <a style="color: #139bd5;" @click="showManageModal(record)">专业管理</a>
          </template>
        </template>
      </a-table>
      <!-- 专业管理模态框 -->
      <a-modal v-model:open="manageModalVisible" title="专业管理" @ok="handleManageOk">
        <a-form :model="manageFormState" name="manage" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off">
          <a-form-item label="院系">
            <a-input v-model:value="manageFormState.department" disabled />
          </a-form-item>
          <a-form-item label="专业">
            <div>
              <a-tag v-for="major in manageFormState.majors" :key="major" closable @close="removeMajor(major)">
                {{ major }}
              </a-tag>
              <a-tag v-if="isAddingMajor" closable @close="cancelAddingMajor">
                <a-input v-model:value="newMajor" @blur="addMajor" @pressEnter="addMajor" />
              </a-tag>
              <a-tag v-else @click="startAddingMajor">
                <a-icon type="plus" /> 添加专业
              </a-tag>
            </div>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-layout-content>
    <a-layout-footer style="text-align: center; color: #ffffff; background-color: #0e6eb8">
      版权所有：河北师范大学顶岗支教指导中心
    </a-layout-footer>
  </a-layout>
</template>



<script setup>
import { ref, computed, reactive } from 'vue';

// 表格绑定表头
const columns = [
  { title: '院系', dataIndex: 'name' },
  { title: '创建时间', dataIndex: 'createdTime' },
  { title: '操作', key: 'operation' },
];

// 数据
const data = ref([
  { createdBy: 'admin',
    createdTime: 1717662199,
    updatedBy: 'admin',
    updatedTime: 1717662199,
    id: 2, 
    name: '数学学院',
    majors: [] 
  },
  { createdBy: 'admin',
    createdTime: 1717763199,
    updatedBy: 'admin',
    updatedTime: 1717763199,
    id: 1,
    name: '软件学院',
    majors: [] },
]);

// 批量删除相关与选中
const state = reactive({
  selectedRowKeys: [],
  loading: false,
  batchDeleting: false,
});

const hasSelected = computed(() => state.selectedRowKeys.length > 0);

const onSelectChange = selectedRowKeys => {
  console.log('selectedRowKeys changed: ', selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};

const handleBatchDelete = () => {
  state.batchDeleting = true;
  const remainingData = data.value.filter(item => !state.selectedRowKeys.includes(item.id));
  setTimeout(() => {
    data.value = remainingData;
    state.batchDeleting = false;
    state.selectedRowKeys = [];
  }, 1000);
};

// 辅助函数：将时间戳转换为人类可读格式
const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp * 1000); // 转换为毫秒
  const yyyy = date.getFullYear();
  const MM = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  const dd = String(date.getDate()).padStart(2, '0');
  const HH = String(date.getHours()).padStart(2, '0');
  const mm = String(date.getMinutes()).padStart(2, '0');
  const ss = String(date.getSeconds()).padStart(2, '0');
  return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
};

const formattedData = computed(() => {
  return data.value.map(item => ({
    ...item,
    key: item.id, // 添加 key 字段用于标识每一项
    createdTime: formatTimestamp(item.createdTime), // 格式化创建时间
    updatedTime: formatTimestamp(item.updatedTime), // 格式化更新时间
  }));
});

// 添加学院模态框相关
const addFormState = ref({ name: '' });
const addModalVisible = ref(false);
const addFormRef = ref(null);

const showAddModal = () => {
  addModalVisible.value = true;
};

const handleAddOk = async () => {
  try {
    await addFormRef.value.validate();
    console.log('Form State:', addFormState.value.name);

    if (!addFormState.value.name) {
      console.log('Form validation failed');
      return;
    }

    const username = localStorage.getItem('username') || 'defaultUser';
    const timestamp = Math.floor(Date.now() / 1000);
    const newId = data.value.length ? Math.max(...data.value.map(item => item.id)) + 1 : 1;

    data.value.push({
      createdBy: username,
      createdTime: timestamp,
      updatedBy: username,
      updatedTime: timestamp,
      id: newId,
      name: addFormState.value.name,
      majors: [],
    });

    addFormState.value.name = '';
    addModalVisible.value = false;

    console.log('New data added', data.value);
  } catch (error) {
    console.log('Form validation failed', error);
  }
};
// 编辑学院按钮的模态框部分
// 编辑学院的表单状态
const editFormState = ref({
  name: '',
});
const editModalOpen = ref(false);
const editFormRef = ref(null);
let editingId = null;

const showEditModal = (record) => {
  editFormState.value.name = record.name;
  editingId = record.id;
  editModalOpen.value = true;
};

const handleEditOk = async () => {
  try {
    await editFormRef.value.validate();
    console.log('Edit Form State:', editFormState.value.name); // 打印表单状态

    // 验证表单输入是否为空
    if (!editFormState.value.name) {
      console.log('Form validation failed');
      return;
    }

    // 更新数据
    const index = data.value.findIndex(item => item.id === editingId);
    if (index !== -1) {
      data.value[index].name = editFormState.value.name;
    }

    // 清空表单并关闭模态框
    editFormState.value.name = '';
    editModalOpen.value = false;

    console.log('Data updated', data.value);
  } catch (error) {
    console.log('Form validation failed', error);
  }
};

// 专业管理模态框相关
const manageFormState = ref({ department: '', majors: [] });
const manageModalVisible = ref(false);
const newMajor = ref('');
const isAddingMajor = ref(false);

const showManageModal = (record) => {
  manageFormState.value.department = record.name;
  manageFormState.value.majors = record.majors || [];
  manageModalVisible.value = true;
};

const handleManageOk = () => {
  const index = data.value.findIndex(item => item.name === manageFormState.value.department);
  if (index !== -1) {
    data.value[index].majors = manageFormState.value.majors;
  }
  manageModalVisible.value = false;
};

const startAddingMajor = () => {
  isAddingMajor.value = true;
};

const addMajor = () => {
  const major = newMajor.value.trim();
  if (major && !manageFormState.value.majors.includes(major)) {
    manageFormState.value.majors.push(major);
  }
  newMajor.value = '';
  isAddingMajor.value = false;
};

const cancelAddingMajor = () => {
  newMajor.value = '';
  isAddingMajor.value = false;
};

const removeMajor = (major) => {
  manageFormState.value.majors = manageFormState.value.majors.filter(m => m !== major);
};

// 单个删除功能
const handleDelete = (id) => {
  data.value = data.value.filter(item => item.id !== id);
};
</script>

<style scoped>
.layout {
  min-height: 100vh;
  width: 100vw;
}
</style>
